﻿using DroidLord.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SharpAdbClient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DroidLord.app.dy
{


    class DYUtils
    {


        //public static DYUserInfoData parseData(string userinfo)
        //{
        //    //MessageBox.Show("" + userinfo);
        //    DYUserInfoData userInfo = new DYUserInfoData();

        //    JObject myobj = (JObject)JsonConvert.DeserializeObject(userinfo);

        //    string statusCode = myobj["status_code"].ToString();
        //    if (statusCode.Equals("0"))
        //    {
        //        userInfo.isParseOk = true;
        //        userInfo.totalFavorited = myobj["total_favorited"].ToString();
        //        userInfo.uniqueId = myobj["unique_id"].ToString();
        //        userInfo.nickName = myobj["nickname"].ToString();
        //        userInfo.signature = myobj["signature"].ToString();
        //        userInfo.awemeCount = myobj["aweme_count"].ToString();
        //        userInfo.followerCount = myobj["follower_count"].ToString();
        //        userInfo.uid = myobj["uid"].ToString();
        //        userInfo.shortId = myobj["short_id"].ToString();
        //        userInfo.followingCount = myobj["following_count"].ToString();
        //        userInfo.favoritingCount = myobj["favoriting_count"].ToString();
        //        string avatar_medium = myobj["avatar_medium"].ToString();
        //        string avatar_thumb = myobj["avatar_thumb"].ToString();
        //        string avatar = "";
        //        if (!avatar_medium.Equals(""))
        //        {
        //            avatar = avatar_medium;
        //        }
        //        else if (!avatar_thumb.Equals(""))
        //        {
        //            avatar = avatar_thumb;
        //        }
        //        if (!avatar.Equals(""))
        //        {
        //            JObject avatarObj = JObject.Parse(avatar);
        //            string urlliststring = myobj["url_list"].ToString();
        //            JArray myarray = JArray.Parse(urlliststring);
        //            if (myarray.Count > 0)
        //            {
        //                userInfo.avatar = myarray[0].ToString();
        //            }
        //        }
        //    }

        //    return userInfo;
        //}

        public  static void  startLiveRoom(DeviceData deviceData,string livid)
        {
            if(DeviceManager.isDeviceOnline(deviceData.Serial))
            {
                string cmd = "am start -a android.intent.action.VIEW -d snssdk1128://live?room_id=" + livid;
                AdbManager.executeShellNoRead(deviceData, cmd);
            }
        }


        public static string  GetRedirectUrl(string urlstring,string uastring)
        {
            string resultUrl = "";
            WebRequest wrt = null;
            WebResponse wrp = null;
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(urlstring);
                httpWebRequest.UserAgent = "" + uastring;
                httpWebRequest.AllowAutoRedirect = true;
                wrp = httpWebRequest.GetResponse();

                resultUrl = wrp.ResponseUri.AbsoluteUri;

            }
            catch (WebException e)
            {
              
            }
            catch (Exception e)
            {
                
            }
            finally
            {
                if (wrp != null)
                    wrp.Close();
                if (wrt != null)
                    wrt.Abort();
            }
            return resultUrl;
        }


        public static string GetData(String url,string uastring)
        {
            WebRequest wrt = null;
            WebResponse wrp = null;
            try
            {
                //live-stream-id=

                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.UserAgent = "" + uastring;

                wrp = httpWebRequest.GetResponse();


                string html = string.Empty;

                using (Stream stream = wrp.GetResponseStream())
                {
                    
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = sr.ReadToEnd();
                    }
                }
                if (html != string.Empty)
                {
                    //JObject jo = (JObject)JsonConvert.DeserializeObject(html);
                    //string sysTime2 = jo["data"]["t"].ToString();
                    if (wrp != null)
                        wrp.Close();
                    if (wrt != null)
                        wrt.Abort();
                    return html;
                }
                else
                {

                }
               

            }
            catch (WebException e)
            {
               

            }
            catch (Exception e)
            {
               

            }
            finally
            {
                if (wrp != null)
                    wrp.Close();
                if (wrt != null)
                    wrt.Abort();
            }
            return "";
        }


        public static string  getVideoInfo(String urlstring,string uastring)
        {
            return GetData(urlstring, uastring);
        }

        public static string GetDYLiveId(string shareUrl,string uastring)
        {
            WebRequest wrt = null;
            WebResponse wrp = null;
            try
            {
                //live-stream-id=
               
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(shareUrl);
                httpWebRequest.UserAgent = ""+uastring;
 
                wrp = httpWebRequest.GetResponse();
               

                string html = string.Empty;

                using (Stream stream = wrp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = sr.ReadToEnd();
                    }
                }
                if (html != string.Empty)
                {
                    //JObject jo = (JObject)JsonConvert.DeserializeObject(html);
                    //string sysTime2 = jo["data"]["t"].ToString();
                   if (wrp != null)
                        wrp.Close();
                    if (wrt != null)
                        wrt.Abort();
                    return html;
                }
                else
                {

                }
                //  MessageBox.Show(year + "-" + month + "-" + day + "" + hour + ":" + minite + ":" + second);

            }
            catch (WebException e)
            {
                //MessageBox.Show("WebException:" + e.ToString());
                //System.DateTime currentTime = System.DateTime.Now;
                //return  currentTime;

            }
            catch (Exception e)
            {
                //MessageBox.Show("Exception:" + e.ToString());
                //System.DateTime currentTime = System.DateTime.Now;
                //return currentTime;

            }
            finally
            {
                if (wrp != null)
                    wrp.Close();
                if (wrt != null)
                    wrt.Abort();
            }
            return "";
        }



        /// <summary>
        /// http下载文件
        /// </summary>
        /// <param name="url">下载文件地址</param>
        /// <param name="path">文件存放地址，包含文件名</param>
        /// <returns></returns>
        public static  bool HttpDownload(string url,string uaString, string path)
        {
            //string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";
            //System.IO.Directory.CreateDirectory(tempPath);  //创建临时文件目录
            //string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //临时文件
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);    //存在则删除
            }
            try
            {
                FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.UserAgent = "" + uaString;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                //Stream stream = new FileStream(tempFile, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    //stream.Write(bArr, 0, size);
                    fs.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                //stream.Close();
                fs.Flush();
                fs.Close();
                responseStream.Close();
               // System.IO.File.Move(tempFile, path);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


    }
}
